package com.wm.wmim.connect.ws.controller;

import com.wm.wmim.common.constant.Constant;
import com.wm.wmim.connect.sdk.onmessage.bo.resp.SendMessageCommonRespBO;
import com.wm.wmim.connect.ws.manager.WebSocketSessionRouteManager;
import com.wm.wmim.connect.ws.manager.WebSocketSessionManager;
import com.wm.wmim.connect.ws.service.OnMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.annotation.Resource;

@Slf4j
@Component
public class WsHandler extends AbstractWebSocketHandler {

    @Resource
    private WebSocketSessionRouteManager webSocketSessionRouteManager;

    @Resource
    private OnMessageService onMessageService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("Connection established, sessionId={}", session.getId());
        // 保存路由
        webSocketSessionRouteManager.saveRouteAndSession(session);
        WebSocketSessionManager.sendMessage(session, "SUCCESS");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理Text消息
        log.info("handleTextMessage sessionId={},message={}", session.getId(), message.getPayload());
        String payload = message.getPayload();
        // 仅转发
        String businessScene = WebSocketSessionManager.getSessionAttribute(session, Constant.WsParamConstant.BUSINESS_SCENE, String.class);
        try {
            SendMessageCommonRespBO respBO = onMessageService.onMessage(businessScene, session.getAttributes(), payload);
            if (respBO.isPush() && StringUtils.isNotEmpty(respBO.getMessage())) {
                WebSocketSessionManager.sendMessage(session, respBO.getMessage());
            }
        } catch (Exception e) {
            log.error("handleTextMessage error! sessionId={},message={}", session.getId(), message.getPayload(), e);
        }
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("Transport error! session={},ex={}", session, exception);
        webSocketSessionRouteManager.removeRouteAndSession(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("Connection closed! session={},closeStatus={}", session, closeStatus);
        webSocketSessionRouteManager.removeRouteAndSession(session);
    }

}